package com.xuzhiguang.lightnat.server.core.server.transfer.processor;

import com.xuzhiguang.lightnat.common.manager.ProxyChannelManager;
import com.xuzhiguang.lightnat.common.message.MessageProcessor;
import com.xuzhiguang.lightnat.common.message.NatMessage;
import com.xuzhiguang.lightnat.server.core.server.transfer.TransferChannelManager;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TransferRequestProcessor implements MessageProcessor {

    @Override
    public void process(ChannelHandlerContext ctx, NatMessage natMessage) {

        log.debug("transfer TransferRequestProcessor. channel:{}", ctx.channel());

        if (natMessage.getBody() instanceof byte[]) {
            Long sessionId = TransferChannelManager.getSessionId(ctx.channel());
            if (sessionId == null) {
                log.warn("sessionId is null. channel:{}", ctx.channel());
                return;
            }
            Channel proxyChannel = ProxyChannelManager.get(sessionId);
            if (proxyChannel == null) {
                log.warn("proxyChannel is null. sessionId:{}", sessionId);
                return;
            }

            // proxy 将请求转发给用户
            proxyChannel.writeAndFlush(natMessage.getBody());
        }
    }
}
